﻿@typeparam TItem where TItem : IDefaultItem<TItem>
@inject I18n I18n

<MListItemContent>
    @{
        var title = I18n.T(Item?.Title);
        var newTitle = GetTitle(title);
        var subtitle = GetSubtitle(title);
        if (!string.IsNullOrWhiteSpace(newTitle))
        {
            <MListItemTitle>@newTitle</MListItemTitle>
        }
        if (!string.IsNullOrWhiteSpace(subtitle))
        {
            <MListItemSubtitle>@subtitle</MListItemSubtitle>
        }
    }
</MListItemContent>

@if (!string.IsNullOrWhiteSpace(Item?.ReleasedOn))
{
    <MChip Class="px-2" Color="@AppService.ColorForNewState" Outlined Small>@Item.ReleasedOn</MChip>
}
else if (Item?.State is not null)
{
    var color = GetColor(Item.State);
    if (Item!.HasChildren())
    {
        <MIcon Color="@color">mdi-circle-medium</MIcon>
    }
    else if (color is null)
    {
        <MChip Color="@Item.StateBackgroundColor" Dark Small>@I18n.T(Item.State)</MChip>
    }
    else
    {
        <MChip Class="px-2" Color="@color" Outlined Small>@I18n.T($"state.{Item.State}")</MChip>
    }
}

@code {

    [Parameter, EditorRequired]
    public TItem? Item { get; set; }

    string? GetColor(string state)
    {
        return state switch
        {
            "new"             => AppService.ColorForNewState,
            "update"          => AppService.ColorForUpdateState,
            "breaking-change" => AppService.ColorForBreakingChangeState,
            "deprecated"      => AppService.ColorForDeprecatedState,
            _                 => null
        };
    }

    string? GetSubtitle(string? title)
    {
        return HandleTitle(title, false);
    }

    string? GetTitle(string? title)
    {
        return HandleTitle(title);
    }

    string HandleTitle(string? title, bool getFirst = true)
    {
        if (string.IsNullOrWhiteSpace(title))
        {
            return string.Empty;
        }

        string[] titles = title.Split("（");

        if (getFirst)
        {
            return titles?.FirstOrDefault() ?? title;
        }
        else
        {
            return titles.Length < 2 ? string.Empty : titles.LastOrDefault()?.Replace("）", "") ?? title;
        }
    }

}
